package com.travelsky.flash.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import com.travelsky.flash.util.log.FlashLogger;
import com.travelsky.flash.vo.CfgFileVO;

/**
 * @Description War包操作工具 
 * @author syuan
 * @date 2015年5月26日  下午1:41:58
 * Company: TravelSky
 */
public class WarUtil {
	
	private static FlashLogger logger = new FlashLogger(WarUtil.class);
	
    private static final int BUFFER = 1024*10;

    /**
     * @Description 压缩文件 
     * @param sourceFilePath
     * @param zipFilePath
     * @return
     * @author syuan
     * @date 2015年5月27日  上午10:19:33
     */
    public static boolean zip(String sourceFilePath,String zipFilePath){
    	logger.info("-------------zip war------------------------");
        boolean result=false;
        File source=new File(sourceFilePath);
        if(!source.exists()){
            logger.info(sourceFilePath+" doesn't exist.");
            return result;
        }
        if(!source.isDirectory()){
            logger.info(sourceFilePath+" is not a directory.");
            return result;
        }
        File zipFile=new File(zipFilePath+"/"+source.getName()+".war");
        if(zipFile.exists()){
            logger.info(zipFile.getName()+" is already exist, delete it.");
            zipFile.delete();
        }else{
            if(!zipFile.getParentFile().exists()){
                if(!zipFile.getParentFile().mkdirs()){
                    logger.info("cann't create file "+zipFile.getName());
                    return result;
                }
            }
        }
        logger.info("creating zip file...");
        FileOutputStream dest=null;
        ZipOutputStream out =null;
        try {
            dest = new FileOutputStream(zipFile);
            CheckedOutputStream checksum = new CheckedOutputStream(dest, new Adler32());
            out=new ZipOutputStream(new BufferedOutputStream(checksum));
            out.setMethod(ZipOutputStream.DEFLATED);
//            从子目录开始压缩
//            compress(source,out,source.getName());
            File[] fs=source.listFiles();
            if(fs!=null&&fs.length>0){
                for(File f:fs){
                    compress(f,out,f.getName());
                }
            }
            result=true;
        } catch (FileNotFoundException e) {
            logger.error(e);
        }finally {
            if (out != null) {
                try {
                    out.closeEntry();
                } catch (IOException e) {
                    logger.error(e);
                }
                try {
                    out.close();
                } catch (IOException e) {
                    logger.error(e);
                }
            }
        }
        if(result){
            logger.info("done.");
        }else{
            logger.info("fail.");
        }
        return result;
    }
    /**
     * @Description 压缩
     * @param file
     * @param out
     * @param mainFileName
     * @author syuan
     * @date 2015年5月26日  下午6:28:22
     */
    private static void compress(File file,ZipOutputStream out,String mainFileName) {
        if(file.isFile()){
            FileInputStream fi= null;
            BufferedInputStream origin=null;
            try {
                fi = new FileInputStream(file);
                origin=new BufferedInputStream(fi, BUFFER);
                int index=file.getAbsolutePath().indexOf(mainFileName);
                String entryName=file.getAbsolutePath().substring(index);
                System.out.println(entryName);
                ZipEntry entry = new ZipEntry(entryName);
                out.putNextEntry(entry);
                byte[] data = new byte[BUFFER];
                int count;
                while((count = origin.read(data, 0, BUFFER)) != -1) {
                    out.write(data, 0, count);
                }
            } catch (FileNotFoundException e) {
                logger.error(e);
            } catch (IOException e) {
                logger.error(e);
            }finally {
                if (origin != null) {
                    try {
                        origin.close();
                    } catch (IOException e) {
                        logger.error(e);
                    }
                }
            }
        }else if (file.isDirectory()){
            File[] fs=file.listFiles();
            if(fs!=null&&fs.length>0){
                for(File f:fs){
                    compress(f,out,mainFileName);
                }
            }
        }
    }

    /**
     * @Description 解压war包
     * @param warFile war路径
     * @param destPath 目标解压路径
     * @return
     * @author syuan
     * @date 2015年5月27日  上午10:05:33
     */
    public static boolean unzipWar(File warFile,String destPath){

    	logger.info("-------------upzip war------------------------");
    	boolean result=false;
    	if(!warFile.exists()){
    		logger.info(warFile.getName()+" doesn't exist.");
    		return result;
    	}
    	// 创建压缩文件同命目录
    	String mainFileName=warFile.getName().replace(".war","");
    	destPath += "/" + mainFileName;
    	File target=new File(destPath);
    	if(!target.exists()){
    		if(!target.mkdirs()){
    			logger.info("cann't create file "+target.getName());
    			return result;
    		}
    	} else {
    		// 删除已存在
    		deleteAll(target);
    		logger.info("delete former directory[" + target.getName() + "]");
    	}
    	
    	// 解压文件
    	ZipInputStream zis =null;
    	logger.info("start unzip file ...");
    	try {
    		FileInputStream fis= new FileInputStream(warFile);
    		CheckedInputStream checksum = new CheckedInputStream(fis, new Adler32());
    		zis = new ZipInputStream(new BufferedInputStream(checksum));
    		ZipEntry entry;
    		while((entry = zis.getNextEntry()) != null) {
    			int count;
    			byte data[] = new byte[BUFFER];
    			String entryName = destPath + "/" + entry.getName();
    			File entryFile = new File(entryName);
    			if(entry.isDirectory()) {
    				// 目录
    				entryFile.mkdirs();
    				
    			} else {
    				FileOutputStream fos = new FileOutputStream(entryName);
        			BufferedOutputStream dest = new BufferedOutputStream(fos,BUFFER);
        			while ((count = zis.read(data, 0, BUFFER)) != -1) {
        				dest.write(data, 0, count);
        			}

        			dest.flush();
        			dest.close();
    			}
    			
    		}
    		result=true;
    	} catch (FileNotFoundException e) {
    		logger.error(e);
    	} catch (IOException e) {
    		logger.error(e);
    	}finally {
    		if (zis != null) {
    			try {
    				if(null != zis)
    					zis.close();
    			} catch (IOException e) {
    				logger.error(e);
    			}
    		}
    	}
    	if(result){
    		logger.info("unzip done.");
    	}else{
    		logger.info("unzip fail.");
    	}
    	return result;
    }
    
    /**
     * @Description 替换文件
     * @param cfgs
     * @return
     * @author syuan
     * @date 2015年5月27日  下午1:54:10
     */
    public static boolean replaceFile(List<CfgFileVO> cfgs){
    	logger.info("-------------replace file------------------------");
    	boolean res = true;
    	byte data[] = new byte[BUFFER];
    	int count;
    	for(CfgFileVO file : cfgs) {
    		if(BaseUtil.stringNotNull(file.getServerDir())) {
    			logger.info("server path: "+file.getServerDir());
    			logger.info("replace path: "+ file.getWarDir());
	    		FileInputStream fis = null;
	    		BufferedInputStream source = null;
	    		FileOutputStream fos = null;
	    		BufferedOutputStream dest = null;
	    		try {
	    			// 新配置文件
		    		fis = new FileInputStream(file.getServerDir());
		    		source = new BufferedInputStream(fis);
		    		
		    		// 目标配置文件
		    		fos = new FileOutputStream(file.getWarDir());
					dest = new BufferedOutputStream(fos,BUFFER);
					while ((count = source.read(data, 0, BUFFER)) != -1) {
						dest.write(data, 0, count);
					}
	    		} catch (IOException e) {
	    			res = false;
					logger.error("", e);
				} finally {
					try {
						if(null != source)
							source.close();
						if (null != fis)
							fis.close();
						if (null != dest)
							dest.close();
						if (null != fos)
							fos.close();
					} catch (IOException e2) {
						res = false;
						logger.error("", e2);
					}
					
				}
    		}

    	}
    	return res;
    }
    
    
    /**
     * @Description 递归删除文件夹目录
     * @param file
     * @author syuan
     * @date 2015年5月27日  上午10:06:09
     */
    private static void deleteAll(File file){  
        if (file.isDirectory() && file.listFiles().length != 0) { 
        	File[] files = file.listFiles();  
            for(File f : files){  
                deleteAll(f);  
                f.delete();  
            } 
        }else {  
            file.delete(); 
        } 
    }

	
    public static void main(String[] args) throws IOException {
//    	// 解压缩
//    	File zipFile=new File("D:/flash.war");
//    	unzipWar(zipFile, "D:/unzip");
    	
    	// 替换配置文件
    	List<CfgFileVO> cfgs = new ArrayList<CfgFileVO>();
    	CfgFileVO file = new CfgFileVO();
    	file.setServerDir("D:/unzip/cfg/log4j.properties");
    	file.setWarDir("D:/unzip"+"/flash"+"/WEB-INF/classes/log4j.properties");
    	cfgs.add(file);
    	replaceFile(cfgs);
//    	
//    	// 再压缩
//    	zip("D:/unzip"+"/flash", "D:/zip");
    }
}
